package com.yiwei.jmx.activity;

import android.annotation.TargetApi;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.allen.library.SuperButton;
import com.viewpagerindicator.LinePageIndicator;
import com.yiwei.jmx.Application;
import com.yiwei.jmx.R;
import com.yiwei.jmx.api.Api;
import com.yiwei.jmx.api.bean.DealApplyDetailBean;
import com.yiwei.jmx.api.bean.LiMuKeyBean;
import com.yiwei.jmx.api.bean.LiMuSignBean;
import com.yiwei.jmx.api.bean.LiMuTokenBean;
import com.yiwei.jmx.base.BaseActivity;
import com.yiwei.jmx.constant.Const;
import com.yiwei.jmx.event.ChangeHomePageEvent;
import com.yiwei.jmx.fragment.IdentityTypeFragment;
import com.yiwei.jmx.util.Network;
import com.yiwei.jmx.util.PreferenceUtils;
import com.yiwei.jmx.util.RxLifeUtil;
import com.yiwei.jmx.util.ToastUtil;
import com.yiwei.jmx.util.Util;
import com.yiwei.jmx.view.V19FrameLayout;
import com.yiwei.jmx.view.ViewHelper;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import kangcheng.com.lmzx_android_sdk_v10.bean.Fuction;
import kangcheng.com.lmzx_android_sdk_v10.bean.MessageEvent;
import kangcheng.com.lmzx_android_sdk_v10.bean.SignEvent;
import kangcheng.com.lmzx_android_sdk_v10.commom.sdk.LmzxSDK;
import kangcheng.com.lmzx_android_sdk_v10.commom.sdk.LmzxSdkImpl;
import kangcheng.com.lmzx_android_sdk_v10.util.callback.DataCallBack;
import kangcheng.com.lmzx_android_sdk_v10.util.callback.ObservableManager;

/**
 * Created by xsooy-pc on 17-12-8.
 */

public class ApplyStatusIngActivity extends BaseActivity implements DataCallBack {

    @BindView(R.id.txt_title)
    TextView txtTitle;

    @BindView(R.id.layout_title)
    V19FrameLayout layoutTitle;
    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.btn_wechat)
    ImageView btnWechat;
    @BindView(R.id.pager)
    ViewPager pager;
    @BindView(R.id.img_status)
    ImageView imgStatus;
    @BindView(R.id.txt_status)
    TextView txtStatus;
    @BindView(R.id.txt_fail_reason)
    TextView txtFailReason;
    @BindView(R.id.btn_earn_money)
    SuperButton btnEarnMoney;
    @BindView(R.id.btn_identity)
    SuperButton btnIdentity;
    @BindView(R.id.layout_success)
    LinearLayout layoutSuccess;
    @BindView(R.id.indicator)
    LinePageIndicator indicator;
    @BindView(R.id.layout_fail)
    LinearLayout layoutFail;
    @BindView(R.id.img_progress_line)
    SuperButton imgProgressLine;
    @BindView(R.id.img_progress_circle)
    ImageView imgProgressCircle;
    @BindView(R.id.img_progress_total)
    SuperButton imgProgressTotal;
    @BindView(R.id.btn_go_identity)
    SuperButton btnGoIdentity;
    @BindView(R.id.layout_identity_all)
    LinearLayout layoutIdentityAll;

    private Unbinder unbiner;
    private static final int TIME = 5 * 1000;  //验证码倒计时时间
    private int selectPoi = 0;
    //    private int[] apply_status_img = new int[]{R.mipmap.img_apply_status_ing, R.mipmap.img_apply_status_fangkuan, R.mipmap.img_apply_status_fail};
    private CountDownTimer timer;
    private int sumFragment = 0;
    public boolean initSuccess = false;
    public String bizType;
    public boolean isFail = false;
    public final static String SUCCESS = "0";
    public final static String LOGING_SUCCESS = "2";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_apply_ing);
        initBar();
        setBarClick();
        unbiner = ButterKnife.bind(this);
        init();
    }

    private void setTimer() {
        timer = new CountDownTimer(TIME, 1000) {

            @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
            @Override
            public void onTick(long millisUntilFinished) {
                try {

                } catch (Resources.NotFoundException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinish() {
                if (pager.getChildCount() > 1) {
                    selectPoi = (selectPoi + 1) % sumFragment;
                    pager.setCurrentItem(selectPoi);
                    timer.start();
                }

            }
        };
    }

    private void init() {

        setTimer();
        pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                selectPoi = position;
                if (sumFragment > 1) {
                    if (timer != null) {
                        timer.cancel();
                        timer.start();
                    } else {
                        setTimer();
                        timer.start();
                    }
                }

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        String deal_id = getIntent().getStringExtra("deal_id");
        getDealApply(deal_id);


    }

    @Override
    protected void onResume() {
        super.onResume();
        getNotCertList();
    }

    private void getDealApply(String deal_id) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.makeText(this, "网络连接失败").show();
            return;
        }
        loadingDialog.show();
        DealApplyDetailBean bean = new DealApplyDetailBean();
        bean.deal_id = deal_id;
        Api.api_service.getDealApplyDetail(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    //借款状态 0 - 申请中，1 - 招标中，2 - 待放款，3 - 审核失败，4 - 还款中，5 - 已还清
                    switch (result.data.deal_status) {
                        case "0":
                            layoutSuccess.setVisibility(View.VISIBLE);
                            ViewGroup.LayoutParams lp = imgProgressLine.getLayoutParams();
                            lp.width = (int) (imgProgressTotal.getWidth() * 0.6);
                            imgProgressLine.setLayoutParams(lp);

                            imgProgressCircle.setImageResource(R.mipmap.img_apply_status_60);
                            ViewHelper.setTranslationX(imgProgressCircle, (float) (imgProgressTotal.getWidth() * 0.6 - imgProgressCircle.getWidth() * 0.5));

                            txtStatus.setText("正在审核中");
                            imgStatus.setImageResource(R.mipmap.img_apply_status_ing);
                            txtTitle.setText("申请审核中");
                            break;
                        case "1":
                            layoutSuccess.setVisibility(View.VISIBLE);
                            ViewGroup.LayoutParams lp1 = imgProgressLine.getLayoutParams();
                            lp1.width = (int) (imgProgressTotal.getWidth() * 0.6);
                            imgProgressLine.setLayoutParams(lp1);

                            imgProgressCircle.setImageResource(R.mipmap.img_apply_status_60);
                            ViewHelper.setTranslationX(imgProgressCircle, (float) (imgProgressTotal.getWidth() * 0.6 - imgProgressCircle.getWidth() * 0.5));


                            txtStatus.setText("正在审核中");
                            imgStatus.setImageResource(R.mipmap.img_apply_status_shenhe);
                            txtTitle.setText("申请审核中");
                            break;
                        case "2":
                            layoutSuccess.setVisibility(View.VISIBLE);
                            ViewGroup.LayoutParams lp2 = imgProgressLine.getLayoutParams();
                            lp2.width = (int) (imgProgressTotal.getWidth() - 30);
                            imgProgressLine.setLayoutParams(lp2);

                            imgProgressCircle.setImageResource(R.mipmap.img_apply_status_100);
                            ViewHelper.setTranslationX(imgProgressCircle, (float) (imgProgressTotal.getWidth() - imgProgressCircle.getWidth()));


                            txtStatus.setText("审核成功正在放款中");
                            imgStatus.setImageResource(R.mipmap.img_apply_status_fangkuan);
                            txtTitle.setText("放款中");
                            break;
                        case "3":
                            layoutSuccess.setVisibility(View.GONE);
                            layoutFail.setVisibility(View.VISIBLE);
                            txtStatus.setText("审核失败");
                            txtFailReason.setText("失败原因：" + result.data.mesg);
                            imgStatus.setImageResource(R.mipmap.img_apply_status_fail);
                            txtTitle.setText("审核失败");
                            break;

                    }
                });
    }


    private void getNotCertList() {
        if (!Network.checkNetwork(this)) {
            ToastUtil.makeText(this, "网络连接失败").show();
            return;
        }
        loadingDialog.show();

        Api.api_service.getNotCertList().compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    if (result.data != null && result.data.size() != 0) {
                        Fragment[] mFragments = new Fragment[result.data.size()];
                        sumFragment = result.data.size();
                        for (int i = 0; i < result.data.size(); i++) {

                            IdentityTypeFragment fragment = new IdentityTypeFragment();
                            Bundle bundle = new Bundle();//声明一个Bundle对象
                            bundle.putParcelable("data", result.data.get(i));
                            fragment.setArguments(bundle);
                            mFragments[i] = fragment;
                        }
                        pager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
                            @Override
                            public Fragment getItem(int position) {

                                return mFragments[position];
                            }

                            @Override
                            public int getCount() {
                                return mFragments.length;
                            }

                        });
                        indicator.setViewPager(pager);
                        indicator.setCurrentItem(0);
                        if (timer != null) {
                            timer.cancel();
                            timer.start();
                        }
                    }else {
                        pager.setVisibility(View.GONE);
                        indicator.setVisibility(View.GONE);
                        layoutIdentityAll.setVisibility(View.VISIBLE);
                    }


                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        LmzxSdkImpl.getInstance().unRegistEvet();
        unbiner.unbind();
        unbiner = null;
    }

    public void getKey(String deal_id, boolean isOperator) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.makeText(this, "网络连接失败").show();
            return;
        }

        LiMuKeyBean bean = new LiMuKeyBean();
        bean.deal_id = deal_id;
        Api.api_service.getLiMuKey(bean).compose(RxLifeUtil.NocheckOn(this)).
                doFinally(() -> {
                    try {

                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    //    初始化立木
                    if (result.getStatus() == 1) {
                        Application.getInstance().LmsdkInit(result.getData().getKey(), result.getData().getUid());
                        LmzxSDK sdk = LmzxSdkImpl.getInstance();
                        sdk.registEvent(this);
                        sdk.setTextStyle(this, 0xFF4a4a4a);
                        sdk.setButtonStyle(this, 0xFF4C81FF);
                        sdk.setPageBack(this, 0xFFf4f4f4);
                        sdk.setBannerTextColor(this, 0xFFFFFFFF);
                        initSuccess = true;

                        if (!isOperator) {
                            return;
                        }
                        switch (bizType) {
                            case Const.IdentityType.yunyin:

                                if (TextUtils.isEmpty(PreferenceUtils.getString(this, "mobile", "")) || Const.IS_DEBUG) {
                                    LmzxSdkImpl.getInstance().initOperatorPreNo(this, "", true);
                                } else {
                                    LmzxSdkImpl.getInstance().initOperatorPreNo(this, PreferenceUtils.getString(this, "mobile", ""), false);
                                }
                                LmzxSdkImpl.getInstance().start(this, Fuction.LMZXSDKFunctionMobileCarrie, 0 + "", Const.LIMU_CALLBACK);
                                break;
                            case Const.IdentityType.car:
                                Util.startActivity(this, CarIdentityActivity.class);
                                break;

                            case Const.IdentityType.face:
//                                LmzxSdkImpl.getInstance().setHTJCParas(this, "true", "0129", "3", "8", "false", "true");
//                                LmzxSdkImpl.getInstance().start(this, Fuction.LMZXSDKHTJC, 0 + "", Const.LIMU_CALLBACK);
                                Util.startActivity(this, FaceIdentityActivity.class);
                                break;
                            case Const.IdentityType.contacts:
                                Util.startActivity(this, IdentityContactActivity.class);
                                break;

                            case Const.IdentityType.email:
//                Util.startActivity(this, V3EmailIdentityActivity.class);
                                break;

                            case Const.IdentityType.face_detect:
                                Util.startActivity(this, FaceIdentityZhiMaActivity.class);
//                                Util.startActivity(this, FaceIdentityActivity.class);
                                break;

                            case Const.IdentityType.house:
                                Util.startActivity(this, HouseIdentityActivity.class);
                                break;

                            case Const.IdentityType.housefund:
                                LmzxSdkImpl.getInstance().start(this, Fuction.LMZXSDKFunctionHousingFund, 0 + "", Const.LIMU_CALLBACK);
                                break;

                            case Const.IdentityType.income:
                                Util.startActivity(this, IncomeIdentityActivity.class);
                                break;

                            case Const.IdentityType.jd:
                                LmzxSdkImpl.getInstance().start(this, Fuction.LMZXSDKFunctionJD, 0 + "", Const.LIMU_CALLBACK);
                                break;
                            case Const.IdentityType.linkedin:
                                LmzxSdkImpl.getInstance().start(this, Fuction.LMZXSDKFunctionLinkedIn, 0 + "", Const.LIMU_CALLBACK);
                                break;

                            case Const.IdentityType.realname:
                                Util.startActivity(this, IdcardIdentityActivity.class);
                                break;

                            case Const.IdentityType.socialsecurity:
                                LmzxSdkImpl.getInstance().start(this, Fuction.LMZXSDKFunctionSocialSecurity, 0 + "", Const.LIMU_CALLBACK);
                                break;

                            case Const.IdentityType.taobao:
                                LmzxSdkImpl.getInstance().start(this, Fuction.LMZXSDKFunctionTaoBao, 0 + "", Const.LIMU_CALLBACK);
                                break;
                            case Const.IdentityType.work:
                                Util.startActivity(this, WorkIdentityActivity.class);
                                break;
                            case Const.IdentityType.xuexin:
                                Util.startActivity(this, V3XueXinIdentityActivity.class);
                                break;
                            case Const.IdentityType.bankcard:
                                Util.startActivity(this, BankBindActivity.class);
                                break;

                        }
                    }
                });
    }

    public void getSign(String params) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.makeText(this, "网络连接失败").show();
            return;
        }


        LiMuSignBean bean = new LiMuSignBean();
        bean.params = params;
        Api.api_service.getSign(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {

                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {

                    HashMap<String, Object> hashMap = new HashMap<>();
                    hashMap.put("sign", result.getSign());
                    //Log.i("signString", "加签结果" + secondSign);
                    ObservableManager.getInstance().doLogic("sign", hashMap); //加签结果传给sdk。key值必须是"sign"。
                });
    }


    public void uploadToken(String deal_id, String token, String biztype) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.makeText(this, "网络连接失败").show();
            return;
        }

        LiMuTokenBean bean = new LiMuTokenBean();
        bean.deal_id = deal_id;
        bean.token = token;
        bean.biztype = biztype;
        Api.api_service.uploadToken(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {

                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    if (result.getStatus() == 1 && !isFail) {
                        ToastUtil.makeText(this, "认证成功", Toast.LENGTH_SHORT).show();
                        getNotCertList();
                    }
                });
    }

    @Override
    public void signData(SignEvent signEvent) {
        String sign = signEvent.getSignStr();//r3qUEj6PhkTz8odjHC0OYTXbtlSxqWyQ  //1.收到sdk传来的字符串
        getSign(sign);
    }

    @Override
    public void messageData(MessageEvent event) {
        MessageEvent test = (MessageEvent) event;
//            Log.i("dasdadsadsadsasa", "code" + test.getCode() + ",message" + test.getMessage() + ",token" + test.getToken() + ",function" + test.getFunction() + ",hasmap" + test.getHashMap().toString());

        if (SUCCESS.equals(((MessageEvent) event).getCode())) {
            //具体哪个业务,参看文档的相关业务类型做处理
            int function = ((MessageEvent) event).getFunction();
            //服务密码
            if (function == Fuction.LMZXSDKFunctionMobileCarrie) {
                //...

            }
            //登录成功处理
        } else if (LOGING_SUCCESS.equals(((MessageEvent) event).getCode())) {
            //可以获取token值,记录提交请求,或者忽略掉
            isFail = false;
            uploadToken("", ((MessageEvent) event).getToken(), bizType);
            //查询失败
        } else {
            isFail = true;
            uploadToken("", ((MessageEvent) event).getToken(), bizType);
            //失败处理,可忽略
//            Log.i("dadasdda", "失败code：" + ((MessageEvent) event).getCode() + "\ntoken=" + ((MessageEvent) event).getToken());
//            Intent intent = new Intent(this, MyIdentityActivity.class);
//            startActivity(intent);
        }
    }

    @OnClick({R.id.btn_earn_money, R.id.btn_identity})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_earn_money:
                EventBus.getDefault().post(new ChangeHomePageEvent(1));
                finish();
                break;
            case R.id.btn_identity:
                EventBus.getDefault().post(new ChangeHomePageEvent(2));
                finish();
                break;
        }
    }

    @OnClick(R.id.btn_go_identity)
    public void onViewClicked() {
        EventBus.getDefault().post(new ChangeHomePageEvent(2));
        finish();
    }
}
